
import time
from typing import Literal
from appium import webdriver
from appium.options.ios import XCUITestOptions
from appium.options.android import UiAutomator2Options
from selenium.webdriver.common.action_chains import ActionChains
import atexit
import cv2
import numpy as np
import base64
from .config import sys_platform
from .utils import write_image


class Driver:
    def __init__(self):
        APPIUM_PORT = 4723
        APPIUM_HOST = '127.0.0.1'
        if sys_platform == "windows":
            capabilities = dict(
                platformName='Android',
                automationName='uiautomator2',
                deviceName='device',
            )
            options = UiAutomator2Options().load_capabilities(capabilities)
        if sys_platform == "macos":
            options = XCUITestOptions()
            options.platform_version = '17.4.1'
            options.udid = '00008110-0016614A3CC3801E'
        options.NEW_COMMAND_TIMEOUT = '30000'

        self.driver = webdriver.Remote(
            f'http://{APPIUM_HOST}:{APPIUM_PORT}', options=options)
        windowSize = self.driver.get_window_size()
        self.windowWidth = windowSize['width']
        self.windowHeight = windowSize['height']
        screenhost = self.getScreenshotForCv2()
        self.pixelWidth = screenhost.shape[1]
        self.pixelHeight = screenhost.shape[0]
        atexit.register(lambda: self.driver.quit())
        print('driver初始化完毕')

    def getScreenshotForCv2(self) -> cv2.Mat:
        return cv2.imdecode(np.frombuffer(base64.b64decode(self.driver.get_screenshot_as_base64()), dtype=np.uint8), flags=cv2.IMREAD_COLOR)

    def saveScreenshot(self, name):
        write_image(name, self.getScreenshotForCv2())

    def tap(self, pixelX: int=None, pixelY:int=None, duration=0.1, timeout=1,direction:Literal["left","top","right","bottom","center"]=None):
        if direction == 'left':
            pixelX = self.pixelWidth/4
            pixelY = self.pixelHeight/2
        if direction == 'top':
            pixelX = self.pixelWidth/2
            pixelY = self.pixelHeight/4
        if direction == 'right':
            pixelX = self.pixelWidth*3/4
            pixelY = self.pixelHeight/2
        if direction == 'bottom':
            pixelX = self.pixelWidth/2
            pixelY = self.pixelHeight*3/4
        if direction == 'center':
            pixelX = self.pixelWidth/2
            pixelY = self.pixelHeight/2
        if sys_platform == "windows":
            if pixelX >= (self.pixelWidth - 150):
                pixelX -= 100
            if pixelX <= 150:
                pixelX += 100

        actions = ActionChains(self.driver)
        windowX = int((pixelX/self.pixelWidth)*self.windowWidth)
        windowY = int((pixelY/self.pixelHeight)*self.windowHeight)
        actions.w3c_actions.pointer_action.move_to_location(windowX, windowY)
        actions.w3c_actions.pointer_action.pointer_down()
        actions.w3c_actions.pointer_action.pause(duration)
        actions.w3c_actions.pointer_action.release()
        actions.perform()
        time.sleep(timeout)

    def swipe(self, startX=0, startY=0, endX=0, endY=0, duration=0.1, timeout=0.2, direction:Literal["left","top","right","bottom"]=None):
        """滑动"""
        """左"""
        if direction == "left":
            startY = self.windowHeight/2
            endY = self.windowHeight/2
            startX = self.windowWidth*3/4
            endX = self.windowWidth/4
        """上"""
        if direction == "top":
            startX = self.windowWidth/2
            endX = self.windowWidth/2
            endY = self.windowHeight/3
            startY = self.windowHeight*2/3
        """右"""
        if direction == "right":
            startY = self.windowHeight/2
            endY = self.windowHeight/2
            startX = self.windowWidth/2 - 100
            endX = self.windowWidth/2 + 100
        """下"""
        if direction == "bottom":
            startX = self.windowWidth/2
            endX = self.windowWidth/2
            startY = self.windowHeight/3
            endY = self.windowHeight*2/3
        if direction == None:
            startX = int((startX/self.pixelWidth)*self.windowWidth)
            startY = int((startY/self.pixelHeight)*self.windowHeight)
            endX = int((endX/self.pixelWidth)*self.windowWidth)
            endY = int((endY/self.pixelHeight)*self.windowHeight)
        self.driver.swipe(startX, startY, endX, endY, duration*1000)
        time.sleep(timeout)

    # def zoomOut(self, timeout=0.5):
    #     """缩小"""
    #     print('缩小')
    #     touchAction1 = TouchAction(self.driver)
    #     touchAction2 = TouchAction(self.driver)
    #     multiAction = MultiAction(self.driver)
    #     touchAction1.press(None, self.windowWidth/2, self.windowHeight*3/4).wait(
    #         100).move_to(None, self.windowWidth/2, self.windowHeight/2).wait(100).release()
    #     touchAction2.press(None, self.windowWidth/2, self.windowHeight/4).wait(
    #         100).move_to(None, self.windowWidth/2, self.windowHeight/2).wait(100).release()
    #     multiAction.add(touchAction1, touchAction2)
    #     multiAction.perform()
    #     time.sleep(timeout)
driver = Driver()
